package com.gali.juc;

import java.util.concurrent.*;
import java.util.concurrent.CompletableFuture;

/**
 * @Auther: gali
 * @Date: 2022-08-18 19:57
 * @Description:
 */
public class CompletableFutureUse {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        extracted();
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        try {
            CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread().getName() + "----start----");
                int result = ThreadLocalRandom.current().nextInt(10);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("-------1秒中后出结果");
                if (result>5){
                    int i =10/0;
                }
                return result;
            },executorService).whenComplete((v,e)->{
                //v代表上一步的result，e代表异常
                if (e==null){
                    System.out.println("计算完成，更新系统value:"+v);
                }
            }).exceptionally(e->{
                e.printStackTrace();
                System.out.println("异常情况："+e.getCause()+"\t"+e.getMessage());
                return null;
            });
            System.out.println(Thread.currentThread().getName()+"先去忙主线程");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }

//        try {
//            TimeUnit.SECONDS.sleep(5);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }

    private static void extracted() throws InterruptedException, ExecutionException {
        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "----start----");
            int result = ThreadLocalRandom.current().nextInt(10);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("-------1秒中后出结果");
            return result;
        });
        System.out.println(Thread.currentThread().getName()+"先去忙主线程");
        System.out.println(integerCompletableFuture.get());
    }
}
